
import {getSongDetail} from '@/services/player';
import * as actionTypes from './constants';

const changeCurrentSongAction = (currentSong)=>({
    type: actionTypes.CHANGE_CURRENT_SONG,
    currentSong
})

const changePlayListAction = (playList) =>({
    type: actionTypes.CHANGE_PLAY_LIST,
    playList
})

const changeCurrentSongIndexAction=(currentSongIndex)=>({
    type:actionTypes.CHANGE_CURRENT_SONG_INDEX,
    currentSongIndex
})

export const changeSequenceAction = (sequence) =>({
    type:actionTypes.CHANGE_SEQUENCE,
    sequence
})

export const getSongDetailAction = (ids) =>{
    return (dispatch,getState)=>{

        const playList=getState().getIn(["player","playList"]);
        const songIndex=playList.findIndex(song=>song.id===ids)

        if(songIndex!==-1){
            dispatch(changeCurrentSongIndexAction(songIndex));
            const song=playList[songIndex]
            dispatch(changeCurrentSongAction(song));
        }else{
            getSongDetail(ids).then(res=>{
                const song=res.songs && res.songs[0];
                if(!song) return;

                const newPlayList=[...playList];
                newPlayList.push(song);

                dispatch(changePlayListAction(newPlayList));
                dispatch(changeCurrentSongIndexAction(newPlayList.length-1));
                dispatch(changeCurrentSongAction(song))
            // console.log(res);
        })
        }
    }
}
